package com.css.project.mobile.controller;

import com.css.common.constant.Constants;
import com.css.common.utils.SecurityUtils;
import com.css.common.utils.http.HttpUtils;
import com.css.framework.security.service.SysLoginService;
import com.css.framework.web.controller.BaseController;
import com.css.framework.web.domain.AjaxResult;
import com.css.project.system.domain.SysUser;
import com.css.project.system.service.ISysUserService;
import com.css.project.weixin.domain.Members;
import com.css.project.weixin.service.IMembersService;
import com.css.project.weixin.domain.UserWeixinRela;
import com.css.project.weixin.service.IMembersService;
import com.css.project.weixin.service.IUserWeixinRelaService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 *移动端登录ctr
 */
@RestController
@RequestMapping(value = "/mobileLogin")
public class MobileLoginController extends BaseController {

    @Autowired
    private IMembersService membersService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IUserWeixinRelaService userWeixinRelaService;

    @PostMapping("/login")
    @ApiOperation("移动端登录及注册")
    public AjaxResult login(@RequestBody Members member){
        AjaxResult ajax = new AjaxResult();
        // 查询member中是否存在该账户
        Members queryMember = membersService.getMembersByOpenId(member.getuOpenid());
        //用户未注册
        if(queryMember==null){
        	//新增微信账户
            membersService.insertMembers(member);
            queryMember = membersService.getMembersByOpenId(member.getuOpenid());
            //新增用户数据
            SysUser user = new SysUser();
            user.setUserName("mobileUser"+member.getuId());//用户名
            user.setPassword(SecurityUtils.encryptPassword("123456"));//密码
            user.setNickName(member.getuName());//用户昵称
            user.setStatus("0");//帐号状态  正常
            user.setDelFlag("0");//删除标志  存在
            user.setCreateBy("admin");//创建人 admin
            user.setCreateTime(new Date());//创建时间
            userService.insertUser(user);
            //新增微信和用户关联数据
            UserWeixinRela userWeixinRela = new UserWeixinRela();
            userWeixinRela.setOpenid(member.getuOpenid());
            userWeixinRela.setUserId(user.getUserId());
            userWeixinRelaService.insertUserWeixinRela(userWeixinRela);

            SysUser user1 = userService.selectUserByUserName(user.getUserName());
            String token = loginService.weixinLogin(user1);
            ajax.put("member", member);
            ajax.put(Constants.TOKEN, token);
            return ajax;
        }else{
            if(queryMember.getuserId()!=null){
                //当前用户已经注册，并且已经微信绑定用户，继续进行用户认证，返回token
                // 生成令牌
                SysUser user = userService.selectUserByUserName(queryMember.getuserName());
                String token = loginService.weixinLogin(user);
                ajax.put("member", queryMember);
                ajax.put(Constants.TOKEN, token);
                return ajax;
            }else{
                //新增用户数据
                SysUser user = new SysUser();
                user.setUserName("mobileUser"+queryMember.getuId());//用户名
                user.setPassword(SecurityUtils.encryptPassword("123456"));//密码
                user.setNickName(member.getuName());//用户昵称
                user.setStatus("0");//帐号状态  正常
                user.setDelFlag("0");//删除标志  存在
                user.setCreateBy("admin");//创建人 admin
                user.setCreateTime(new Date());//创建时间
                userService.insertUser(user);
                //新增微信和用户关联数据
                UserWeixinRela userWeixinRela = new UserWeixinRela();
                userWeixinRela.setOpenid(member.getuOpenid());
                userWeixinRela.setUserId(user.getUserId());
                userWeixinRelaService.insertUserWeixinRela(userWeixinRela);
                SysUser user1 = userService.selectUserByUserName(user.getUserName());
                String token = loginService.weixinLogin(user1);
                ajax.put("member", queryMember);
                ajax.put(Constants.TOKEN, token);
                return ajax;
            }
        }
    }

    @PostMapping("/loginByWeiXinBind")
    @ApiOperation("移动端登录及注册")
    public AjaxResult loginByWeiXinBind(@RequestBody Members member){
        AjaxResult ajax = new AjaxResult();
        // 查询member中是否存在该账户
        Members queryMember = membersService.getMembersByOpenId(member.getuOpenid());
        //用户未注册
        if(queryMember==null){
            membersService.insertMembers(member);
            queryMember = membersService.getMembersByOpenId(member.getuOpenid());
            //ajax.put("member", queryMember);
            return AjaxResult.error("注册成功,请联系系统管理员进行微信绑定！");
        }else{
            if(queryMember.getuserId()!=null){
                //当前用户已经注册，并且已经微信绑定用户，继续进行用户认证，返回token
                // 生成令牌
                SysUser user = userService.selectUserByUserName(queryMember.getuserName());
                String token = loginService.weixinLogin(user);
                ajax.put("member", queryMember);
                ajax.put(Constants.TOKEN, token);
                return ajax;
            }else{
                return AjaxResult.error("当前用户已经注册,请联系系统管理员进行微信绑定！");
            }
        }
    }

    @GetMapping("/getWeiXinSession")
    @ApiOperation("根据code获取微信的openID和sessionKey")
    public String getWeiXinSession(@RequestParam String code,@RequestParam String appid,
                                       @RequestParam String secret)
    {
        AjaxResult ajax = new AjaxResult();
        //调用微信接口
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String param = "appid="+ appid +"&secret="+ secret + "&js_code="+ code +"&grant_type=authorization_code";
        String result = HttpUtils.sendGet(url,param);
        System.out.print(result);
        return result;
    }
}
